<?php
namespace app\admin\controller;
use think\Db;
use think\Request;
use think\Controller;
class Article extends Common
{
    public function index(){
		$key=input('post.key');
        $this->assign('testkey',$key);
        $list=db('article')->where('title','like',"%".$key."%")->order('listorder desc')->select();
        $this->assign('list',$list);
		return $this->fetch();	
	}
	
	public function add(){
		if(request()->isPost()) {
            //构建数组
            $data = input('post.');
            $data['add_time'] = time();
            $r = db('article')->insert($data);
			if($r){
				$result['code'] = 1;
				$result['msg'] = '添加成功!';
				$result['url'] = url('index');
			}else{
				$result['code'] = 0;
				$result['msg'] = '添加失败!';
				$result['url'] = '';
			}
            return $result;
        }else{
			$this->assign('title','添加内容');
			$this->assign('info','null');
			return $this->fetch('form');	
		}
	}
	
	public function edit(){
		if(request()->isPost()) {
            //构建数组
            $data = input('post.');
            $data['up_time'] = time();
            $r = db('article')->update($data);
			if($r){
				$result['code'] = 1;
				$result['msg'] = '编辑成功!';
				$result['url'] = url('index');
			}else{
				$result['code'] = 0;
				$result['msg'] = '编辑失败!';
				$result['url'] = '';
			}
            return $result;
        }else{
			$this->assign('title','编辑内容');
			$id=input('id');
            $info=db('article')->where(array('id'=>$id))->find();
            $this->assign('info',json_encode($info,true));
			return $this->fetch('form');	
		}
	}
	
	public function editState(){
        $id=input('post.id');
        $open=db('article')->where(array('id'=>$id))->value('status');//判断当前状态情况
        if($open==1){
            $data['status'] = 0;
            db('article')->where(array('id'=>$id))->setField($data);
            $result['status'] = 1;
            $result['info'] = '状态禁止';
        }else{
            $data['status'] = 1;
            db('article')->where(array('id'=>$id))->setField($data);
            $result['status'] = 1;
            $result['info'] = '状态开启';
        }
        return $result;
    }
	public function adOrder(){
        $ad=db('article');
        foreach (input('post.') as $id => $sort){
            $ad->where(array('id' => $id ))->setField('listorder' , $sort);
        }
        $result['code'] = 1;
        $result['msg'] = '内容排序更新成功';
        $result['url'] = url('index');
        return $result;
    }
}